import { defineStore } from "pinia";

const TOKEN_KEY = "token";
const USER_INFO_KEY = "user_info";
const USER_TYPE_KEY = "user_type";
const MERCHANT_TYPE_KEY = "merchant_type";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: localStorage.getItem(TOKEN_KEY) || null,
    userInfo: JSON.parse(localStorage.getItem(USER_INFO_KEY) || "null"),
    userType: localStorage.getItem(USER_TYPE_KEY) || null,
    merchantType: localStorage.getItem(MERCHANT_TYPE_KEY) || null,
    loading: false,
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    isMerchant: (state) => state.userType === "merchant",
    isAdmin: (state) => state.userType === "admin",
    isHotelMerchant: (state) =>
      (state.userType === "merchant" && state.merchantType === "hotel") ||
      state.userType === "hotel",
    isCulturalMerchant: (state) =>
      state.userType === "merchant" && state.merchantType === "cultural",
    username: (state) => state.userInfo?.username || "",
    avatar: (state) => state.userInfo?.avatar || "",
  },

  actions: {
    setToken(token) {
      if (!token) {
        this.token = null;
        localStorage.removeItem(TOKEN_KEY);
        return;
      }
      
      this.token = token;
      localStorage.setItem(TOKEN_KEY, token);
    },

    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      if (userInfo) {
        localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo));
      } else {
        localStorage.removeItem(USER_INFO_KEY);
      }
    },

    setUserType(userType) {
      this.userType = userType;
      if (userType) {
        localStorage.setItem(USER_TYPE_KEY, userType);
      } else {
        localStorage.removeItem(USER_TYPE_KEY);
      }
    },

    setMerchantType(merchantType) {
      this.merchantType = merchantType;
      if (merchantType) {
        localStorage.setItem(MERCHANT_TYPE_KEY, merchantType);
      } else {
        localStorage.removeItem(MERCHANT_TYPE_KEY);
      }
    },

    clearUserData() {
      this.token = null;
      this.userInfo = null;
      this.userType = null;
      this.merchantType = null;
      localStorage.removeItem(TOKEN_KEY);
      localStorage.removeItem(USER_INFO_KEY);
      localStorage.removeItem(USER_TYPE_KEY);
      localStorage.removeItem(MERCHANT_TYPE_KEY);
    },

    async login(credentials) {
      this.loading = true;
      try {
        // 获取用户标识（email或phone）
        const userIdentifier = credentials.email || credentials.phone || "";
        
        // TODO: 实现登录API调用
        const response = await new Promise((resolve) =>
          setTimeout(
            () =>
              resolve({
                token: "mock_token",
                userInfo: {
                  id: 1,
                  username: userIdentifier.split('@')[0], // 如果是邮箱，取@前面的部分作为用户名
                  email: credentials.email || null,
                  phone: credentials.phone || null,
                  avatar: "/default-avatar.png",
                },
                userType: credentials.userType,
                merchantType:
                  credentials.userType === "merchant"
                    ? credentials.merchantType
                    : null,
              }),
            1000,
          ),
        );

        this.setToken(response.token);
        this.setUserInfo(response.userInfo);
        this.setUserType(response.userType);
        this.setMerchantType(response.merchantType);
        return true;
      } catch (error) {
        console.error("Login failed:", error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    async loginWithPhone(credentials) {
      this.loading = true;
      try {
        // TODO: 实现手机验证码登录API调用
        const response = await new Promise((resolve) =>
          setTimeout(
            () =>
              resolve({
                token: "mock_token",
                userInfo: {
                  id: 1,
                  phone: credentials.phone,
                  avatar: "/default-avatar.png",
                },
              }),
            1000,
          ),
        );

        this.setToken(response.token);
        this.setUserInfo(response.userInfo);
        return true;
      } catch (error) {
        console.error("Phone login failed:", error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    async register(userData) {
      this.loading = true;
      try {
        // TODO: 实现注册API调用
        const response = await new Promise((resolve) =>
          setTimeout(
            () =>
              resolve({
                token: "mock_token",
                userInfo: {
                  id: 1,
                  username: userData.username,
                  avatar: "/default-avatar.png",
                },
              }),
            1000,
          ),
        );

        this.setToken(response.token);
        this.setUserInfo(response.userInfo);
        return true;
      } catch (error) {
        console.error("Registration failed:", error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    async resetPassword(data) {
      this.loading = true;
      try {
        // TODO: 实现重置密码API调用
        await new Promise((resolve) => setTimeout(resolve, 1000));
        return true;
      } catch (error) {
        console.error("Password reset failed:", error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    logout() {
      this.clearUserData();
    },

    updateAvatar(avatarUrl) {
      if (this.userInfo) {
        this.userInfo.avatar = avatarUrl;
        localStorage.setItem(USER_INFO_KEY, JSON.stringify(this.userInfo));
      }
    },
  },
});
